<template>
  <div class="select-tree-component">
    <div class="select-block app-el-form-item" @click="handleOpen">
      <template v-if="value.length === 0">
        <span class="placeholder">{{ placeholder }}</span>
      </template>
      <template v-for="(tagItem, index) in value" v-else>
        <span :key="index" class="select-tag">
          <span>{{ tagItem.label }}</span>
          <span class="el-icon-close" @click="(e)=> { handleDelete(e,tagItem) }" />
        </span>
      </template>

      <span :class="{'icon-select': true, 'open': selecting}">
        <span class="el-icon-arrow-up" />
      </span>
    </div>
    <template v-if="selecting">
      <select-view
        visible
        :title="title"
        :data="optionList"
        :value="value"
        @close="selecting = false"
        @submit="handleTreeSubmit"
      />
    </template>
  </div>
</template>

<script>
import SelectView from './selectView'
export default {
  name: 'SelectTree',
  components: { SelectView },
  props: {
    value: {
      type: Array,
      default: () => []
    },
    optionList: {
      type: Array,
      default: () => []
    },
    placeholder: {
      type: String,
      default: () => '请选择'
    },
    title: {
      type: String,
      default: '请选择'
    }
  },
  data() {
    return {
      selecting: false
    }
  },
  methods: {
    handleOpen() {
      this.$data.selecting = true
    },
    handleTreeSubmit(e) {
      this.$emit('input', e)
      this.$emit('change', e)
      this.$data.selecting = false
    },
    handleDelete(e, currnet) {
      e.stopPropagation()
      const nowValue = this.$props.value.filter(e => e.id !== currnet.id)
      this.$emit('input', nowValue)
      this.$emit('change', nowValue)
    }
  }
}
</script>

<style lang="scss" scoped>
  .select-block {
    line-height: 28px;
    min-height: 28px;

    cursor: pointer;
    position: relative;

    // 标签
    .select-tag{
      background-color: #f4f4f5;
      border-color: #e9e9eb;
      color: #909399;
      font-size: 12px;
      padding: 2px 5px;
      border-radius: 4px;
      border: 1px solid #e9e9eb;
      margin-right: 4px;

      .el-icon-close{
        border-radius: 50%;
        text-align: center;
        position: relative;
        cursor: pointer;
        font-size: 12px;
        height: 16px;
        width: 16px;
        line-height: 16px;
        vertical-align: middle;
        background-color: #C0C4CC;
        transform: scale(0.7);

        &:hover {
          background-color: #aaadb3;
          color: #f4f4f5;
        }
      }
    }

    // 右侧下拉图标
    .icon-select {
      position: absolute;
      right: 0;
      top: 0;
      width: 28px;
      color: #DCDFE6;
      text-align: center;
      transition: 0.3s transform;
      transform: rotateZ(180deg);

      &.open {
        transform: rotateZ(0deg);
      }
    }
  }
</style>
